import urllib, json, subprocess

URL = 'http://github.com/'
API = 'http://github.com/api/v2/json/repos/'
NAME = 'github'
VERSION_CONTROL = 'git'

def api_search(arg):
    f = urllib.urlopen(API + 'search/' + arg)
    f = json.loads(f.read())
    return f['repositories']

def api_info(user, name):
    f = urllib.urlopen(API + "show/" + user + '/' + name)
    f = json.loads(f.read())
    return f['repository']

def search(arg):
    ret = []
    s = api_search(arg)
    for each in s:
        n = {'name' : each['name'], 'description' : each['description']}
        ret.append(n)

    return ret

def info(arg):
    info = {}
    s = api_search(arg)
    for repo in s:
        if repo['name'] == arg:
            info = {'name' : repo['name'], 'description' : repo['description'], 'owner' : repo['username'], 'language' : repo['language']}
            break
    if not info:
        return info

    i = api_info(info['owner'], info['name'])
    for param in ('url', 'homepage', 'open_issues'):
        info[param] = i[param]
    return info

def download(arg, verbose=True):
    i = info(arg)
    if not i:
        return False
    git_url = i['url'].replace('http', 'git') + '.git'
    if verbose:
        ret = subprocess.Popen("git clone " + git_url, shell=True)
    else:
        ret = subprocess.Popen("git clone " + git_url, shell=True, stdout=subprocess.PIPE)
    ret.wait()
    return True
